package com.newlink.building.common_base.http.interceptor

import com.newlink.building.common_base.constant.Base_HttpConstant
import okhttp3.Interceptor
import okhttp3.Response

class Base_SaveCookieInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val response = chain.proceed(request)
        val requestUrl = request.url.toString()
        val domain = request.url.host
        // set-cookie maybe has multi, login to save cookie
        if ((requestUrl.contains(Base_HttpConstant.SAVE_USER_LOGIN_KEY)
                    || requestUrl.contains(Base_HttpConstant.SAVE_USER_REGISTER_KEY))
            && !response.headers(Base_HttpConstant.SET_COOKIE_KEY).isEmpty()
        ) {
            val cookies = response.headers(Base_HttpConstant.SET_COOKIE_KEY)
            val cookie = Base_HttpConstant.encodeCookie(cookies)
            Base_HttpConstant.saveCookie(requestUrl, domain, cookie)
        }
        return response
    }
}